package com.udima.reglocation.util;

import java.util.ArrayList;
import java.util.List;

import com.udima.reglocation.entities.Track;



import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class SQLiteDatabaseHandler extends SQLiteOpenHelper {

	static final int DATABASE_VERSION = 4;
	
    public SQLiteDatabaseHandler(Context context) {
        super(context, "tracks", null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {   	
    	
        String CREATE_TRACKS_TABLE = "CREATE TABLE tracks (" +
        		"time DATETIME DEFAULT (datetime(current_timestamp,'localtime'))," +
        		"latitude REAL," +
        		"longitude REAL," +
        		"altitude REAL," +
        		"speed REAL)";
        db.execSQL(CREATE_TRACKS_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    	db.execSQL("DROP TABLE IF EXISTS tracks");
    	onCreate(db);
    }
    
    public void clearTable() {
    	SQLiteDatabase db = this.getWritableDatabase();
        String DELETE_TRACKS_TABLE = "DELETE FROM tracks";
        db.execSQL(DELETE_TRACKS_TABLE);
      }

	public void insertRow(Double latitude, Double longitude, Double altitude, Float speed) {
	    SQLiteDatabase db = this.getWritableDatabase();
	    ContentValues values = new ContentValues();
	
	    values.put("latitude", latitude);
	    values.put("longitude", longitude);
	    values.put("altitude", altitude);
	    values.put("speed", speed);
	
	    db.insert("tracks", null, values);
	    db.close();
	}

	public List<Track> getAllTracks() {
      List<Track> trackList = new ArrayList<Track>();
      String selectQuery = "SELECT latitude, longitude, altitude, speed, time FROM tracks";

      SQLiteDatabase db = this.getWritableDatabase();
      Cursor cursor = db.rawQuery(selectQuery, null);

      if (cursor.moveToFirst()) {
          do {
              Track track = new Track();
              track.setLatitude(Double.parseDouble(cursor.getString(0)));
              track.setLongitude(Double.parseDouble(cursor.getString(1)));
              track.setAltitude(Double.parseDouble(cursor.getString(2)));
              track.setSpeed(Float.parseFloat(cursor.getString(3)));
              track.setTime(cursor.getString(4));            
              trackList.add(track);
          } while (cursor.moveToNext());
      }

      cursor.close();
      db.close();
      return trackList;
	}
}
